import { useState, useEffect, useCallback } from "react";
import { Button, Input, List, Space, Tag, Modal } from "antd";
import { message } from "../../utils/customMessage";
import {
  SearchOutlined,
  ClearOutlined,
  DownloadOutlined,
  EyeOutlined,
  DeleteOutlined,
  FileTextOutlined,
} from "@ant-design/icons";
import FilePreview from "../components/filePreview";
import { useParams } from "react-router-dom";
import { http } from "../../utils/request";

interface FileItem {
  id: number;
  fileName: string;
  filePath: string;
  fileUrl: string | null;
  updateTime: string;
  fileContent?: string;
}

const Home = () => {
  const [searchValue, setSearchValue] = useState("");
  const [fileList, setFileList] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [userInfo, setUserInfo] = useState<any>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null);
  const [contentModalVisible, setContentModalVisible] = useState(false);
  const [currentFileContent, setCurrentFileContent] = useState<string>("");
  const [currentFileName, setCurrentFileName] = useState<string>("");
  const params = useParams();

  const fetchUserInfo = async () => {
    try {
      const userId = localStorage.getItem("userId");

      if (!userId) {
        message.error("未找到用户ID");
        return;
      }

      const result = await http.get(`/api/user/userInfo?id=${userId}`);

      if (+result.status === 200 && result.data) {
        setUserInfo(result.data);
        localStorage.setItem("userInfo", JSON.stringify(result.data));
      } else {
        message.error(result.message || "获取用户信息失败");
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
      message.error("获取用户信息失败");
    }
  };

  const getMenuId = (path: string): number | null => {
    if (path === "/home" && !userInfo) {
      return 1;
    }

    if (!userInfo?.role?.menuList) {
      console.log("没有菜单权限信息");
      return null;
    }

    try {
      const findMenuId = (menus: any[]): number | null => {
        for (const menu of menus) {
          if (menu.path === path || menu.url === path) {
            return menu.id;
          }
          const children = menu.menuList || menu.children;
          if (children && children.length > 0) {
            const found = findMenuId(children);
            if (found) return found;
          }
        }
        return null;
      };

      const menuId = findMenuId(userInfo.role.menuList);

      if (!menuId && path === "/home") {
        return 1;
      }

      return menuId;
    } catch (error) {
      console.error("解析菜单信息失败:", error);
      if (path === "/home") {
        return 1;
      }
      return null;
    }
  };

  const fetchFileList = useCallback(async () => {
    if (!userInfo) return;

    try {
      setLoading(true);
      const currentPath = location.pathname;
      const menuId = getMenuId(currentPath);

      if (!menuId) {
        message.error("获取菜单ID失败");
        return;
      }

      const result = await http.get(
        `/api/uploadFile/getFileList?menuId=${menuId}`
      );

      if (+result.status === 200) {
        setFileList(result.data);
      } else {
        message.error(result.message || "获取文件列表失败");
      }
    } catch (error) {
      message.error("获取文件列表失败");
    } finally {
      setLoading(false);
    }
  }, [userInfo, params]);

  useEffect(() => {
    fetchUserInfo();
  }, []);

  useEffect(() => {
    if (userInfo) {
      fetchFileList();
    }
  }, [userInfo, fetchFileList]);

  const handleSearch = async () => {
    if (!searchValue.trim()) {
      message.warning("请输入搜索关键词");
      return;
    }

    if (!userInfo) {
      message.error("用户信息未加载");
      return;
    }

    try {
      setLoading(true);
      const { current, pageSize } = pagination;

      const result = await http.get(
        `/api/uploadFile/searchFile?searchContent=${searchValue}&page=${current}&pageSize=${pageSize}`
      );

      if (+result.status === 200) {
        setFileList(result.data.records);
        setPagination({
          ...pagination,
          total: result.data.total,
        });
      } else {
        message.error(result.message || "搜索失败");
      }
    } catch (error) {
      message.error("搜索失败");
    } finally {
      setLoading(false);
    }
  };

  const handleClear = () => {
    setSearchValue("");
    if (userInfo) {
      fetchFileList();
    }
  };

  const handleDownload = (item: FileItem) => {
    if (!item.fileUrl) {
      message.error("文件地址不存在");
      return;
    }

    const link = document.createElement("a");
    link.href = item.fileUrl;
    link.download = item.fileName;
    link.target = "_blank";
    link.rel = "noopener noreferrer";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const handlePreview = (item: FileItem) => {
    setPreviewFile(item);
    setPreviewVisible(true);
  };

  // 处理预览文件内容
  const handlePreviewContent = (item: FileItem) => {
    setCurrentFileContent(item.fileContent || "暂无内容");
    setCurrentFileName(item.fileName);
    setContentModalVisible(true);
  };

  const getFileTypeColor = (type: string): string => {
    const typeMap: Record<string, string> = {
      xlsx: "green",
      xls: "green",
      doc: "blue",
      docx: "blue",
      pdf: "red",
      txt: "default",
    };
    return typeMap[type.toLowerCase()] || "default";
  };

  const handleDelete = async (fileId: number) => {
    try {
      const result = await http.post(`/api/uploadFile/deleteFile/${fileId}`);

      if (+result.status === 200) {
        message.success("删除成功");
        fetchFileList();
      } else {
        message.error(result.message || "删除失败");
      }
    } catch (error) {
      message.error("删除失败");
    }
  };

  return (
    <div style={{ padding: "20px" }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          marginBottom: "20px",
          gap: "16px",
        }}
      >
        <div
          style={{
            flex: 1,
            display: "flex",
            gap: "8px",
            maxWidth: "800px",
            margin: "0 auto",
          }}
        >
          <Input
            placeholder="请输入搜索关键词"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={handleSearch}
            style={{ width: "100%" }}
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={handleSearch}
          >
            搜索
          </Button>
          <Button icon={<ClearOutlined />} onClick={handleClear}>
            清空
          </Button>
        </div>
      </div>

      <List
        loading={loading}
        dataSource={fileList}
        pagination={false}
        itemLayout="horizontal"
        renderItem={(item: FileItem) => (
          <List.Item
            actions={[
              <Button
                key="preview"
                type="link"
                icon={<EyeOutlined />}
                onClick={() => handlePreview(item)}
              >
                预览
              </Button>,
              <Button
                key="preview-content"
                type="link"
                icon={<FileTextOutlined />}
                onClick={() => handlePreviewContent(item)}
                disabled={!item.fileContent}
              >
                预览局部
              </Button>,
              <Button
                key="download"
                type="link"
                icon={<DownloadOutlined />}
                onClick={() => handleDownload(item)}
              >
                下载
              </Button>,
              <Button
                key="delete"
                type="link"
                danger
                icon={<DeleteOutlined />}
                onClick={() => handleDelete(item.id)}
              >
                删除
              </Button>,
            ]}
          >
            <List.Item.Meta
              title={
                <div>
                  <Space style={{ marginBottom: "4px" }}>
                    <span>{item.fileName}</span>
                    <Tag
                      color={getFileTypeColor(
                        item.fileName.split(".").pop() || ""
                      )}
                    >
                      {item.fileName.split(".").pop()?.toUpperCase()}
                    </Tag>
                  </Space>
                  {item.fileContent && (
                    <div
                      style={{
                        fontSize: "12px",
                        color: "#666",
                        marginTop: "4px",
                        lineHeight: "1.4",
                      }}
                    >
                      {item.fileContent.length > 50
                        ? `${item.fileContent.substring(0, 50)}...`
                        : item.fileContent}
                    </div>
                  )}
                </div>
              }
              description={`路径: ${item.filePath} | 更新时间: ${item.updateTime}`}
            />
          </List.Item>
        )}
        virtual
        height={500}
        itemHeight={73}
      />

      <FilePreview
        visible={previewVisible}
        file={previewFile}
        onClose={() => setPreviewVisible(false)}
        searchText={searchValue.trim() || undefined}
      />

      {/* 文件内容预览弹窗 */}
      <Modal
        title={`文件内容预览 - ${currentFileName}`}
        open={contentModalVisible}
        onCancel={() => setContentModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setContentModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={1200}
        centered
      >
        <div
          style={{
            maxHeight: "60vh",
            overflowY: "auto",
            padding: "16px",
            backgroundColor: "#f8f9fa",
            borderRadius: "4px",
            fontFamily: "monospace",
            fontSize: "14px",
            lineHeight: "1.6",
            whiteSpace: "pre-wrap",
            wordBreak: "break-word",
          }}
        >
          {currentFileContent}
        </div>
      </Modal>
    </div>
  );
};

export default Home;
